﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using Bongiozzo.Properties;

namespace Bongiozzo.Models
{
    public class Tweet
    {
        public string Id;
        public string Text;
        public DateTime TimeStamp;
    }

    public class TwitterModel
    {
        public TwitterModel()
        { 
            TwitterProfileName = Settings.Default.UserName;
        }

        //Twitter profile name or screen name.
        public String TwitterProfileName { get; set; }
        
        private static XDocument xDoc = null; //static variable to store the result xml.
        private static IEnumerable<Tweet> tweets = null;
    
        private DateTime parseTwitterTime(string date)
        {
            string format = "ddd MMM dd HH:mm:ss zzzz yyyy";
            return DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
        }
        
        public IEnumerable<Tweet> GetTweets(int tweetsCount)
        {
            var xml = LoadXML();
            if (xml != null)
            {
                tweets = from e in xml.Descendants("status").TakeWhile((tweet, index) => index < tweetsCount)
                        select new Tweet
                        {
                            Text = e.Element("text").Value,
                            Id = e.Element("id").Value,
                            TimeStamp = parseTwitterTime(e.Element("created_at").Value)
                        };
            }
            return tweets;
        }

        private XDocument LoadXML()
        {
            try
            {
                var url = string.Format("https://api.twitter.com/1/statuses/user_timeline.xml?screen_name={0}&count=20&exclude_replies=true&trim_user=1", TwitterProfileName);
                xDoc = XDocument.Load(url);
                return xDoc;
            }
            catch
            {
                return null;
            }
        }
    }
}